package com.yincheng.oms.sso.service;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.yincheng.oms.sso.entity.User;
import com.yincheng.oms.sso.mapper.UserMapper;
import com.yincheng.oms.sso.util.UserUtils;

/**
 * 
 * @author yangsy
 * @version 1.0.0
 * @since 
 * 创建时间：2018年7月11日
 * 功能描述：登录时针对访问请求预处理类
 * 邮箱地址：446948434@qq.com
 */
public class SingleUserInterceptor implements HandlerInterceptor {
	
	@Autowired
	private UserMapper userMapper;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String url = request.getRequestURI();
		// 如果拦截到的是登录校验的话放行
		if (url.indexOf("checkLogin") >= 0 ) {
			return true;
		}
		// 如果拦截到的是登录的页面的话放行
		if (url.indexOf("login.jsp") >= 0 || url.indexOf("login") >= 0 || url.indexOf("toLogin") >= 0) {
			return true;
		}
		// 如果拦截到的是获取验证码的话放行
		if (url.indexOf("getCode") >= 0) {
			return true;
		}
		// 如果拦截到的是注册账号的话放行
		if (url.indexOf("register") >= 0) {
			return true;
		}
		// 如果拦截到的是重置密码的话放行
		if (url.indexOf("resetPsd") >= 0) {
			return true;
		}
		
		String userAccount = (String) request.getSession().getAttribute("userAccount");
		if (userAccount != null) {
			User account = userMapper.selectByUserAccount(userAccount);
			String sessionId = account.getSessionId();
			if (sessionId.equals(request.getSession().getId())) {
				
				//保存用户信息到当前线程中
				UserUtils.set(account);
				return true;
			} else {
				response.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
				response.setContentType("text/html; charset=utf-8");
				PrintWriter out = response.getWriter();
				out.println("<html>");
				out.println("<script>");
				out.println("alert('您的账号在别地登录，您被迫下线')");
				out.println("window.open ('" + request.getContextPath() + "/login','_top');");
				out.println("</script>");
				out.println("</html>");
				// request.getRequestDispatcher("login.jsp").forward(request,response);
				return false;
			}
		}
		request.getRequestDispatcher("login.jsp").forward(request, response);
		return false;

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
